
$(document).ready(function () {

    /***等待图****/
    var opts = {
        lines: 9, // The number of lines to draw
        length: 0, // The length of each line
        width: 12, // The line thickness
        radius: 43, // The radius of the inner circle
        scale: 1.05, // Scales overall size of the spinner
        corners: 1, // Corner roundness (0..1)
        color: '#01CBE9', // CSS color or array of colors
        fadeColor: 'transparent', // CSS color or array of colors
        speed: 1, // Rounds per second
        rotate: 0, // The rotation offset
        animation: 'spinner-line-fade-quick', // The CSS animation name for the lines
        direction: 1, // 1: clockwise, -1: counterclockwise
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        className: 'spinner', // The CSS class to assign to the spinner
        top: '34%', // Top position relative to parent
        left: '50%', // Left position relative to parent
        shadow: '0 0 1px transparent', // Box-shadow for the lines
        position: 'absolute' // Element positioning
    };

    var target = document.getElementById('spin');
    var spinner = new Spinner(opts).spin(target);

    /*******/
    var Request = new searchUrl(),//地址参数化。方法来自base.jsx
        id = Request.id,           //productid的
        from = Request.from,      //来源
        userInfo = getUserInfo(),  //获取用户信息，主要用于对管理员的处理
        d = getPlatform(),          //获取的设备信息
        groupId = '',                //获取产品社区id
        sourceUrl=Request.historyUrl;
        sessionStorage.setItem('productId', id);//存储当前页面的id，用于返回时查找

    /******getProduct*******/
    myAjaxFunc({
        url: geturl + "getProduct",
        type: 'post',
        dataType: 'json',
        data: {id: id, platform: "pc/type:" + d},
        mySuccess: function (data) {

            if (isResponseSuccess('success', data)){

                $('#spin').fadeOut();
                $('main').fadeIn();

            var content = data.data.product;
            groupId = content.group.id;

            $('#productGroupName').html(content.group.name);
            $('#groupPostTopPostMore').attr('href','groupItem.html?groupId='+content.group.id);
            $('#groupPostTopPost').attr('href','userSendPost.html?groupId='+content.group.id+'&groupName='+content.group.name);


            $('#productLogo').attr('src', geturlimg + content.logoUrl);

            $('.productName,.navProductName').text(content.name);

            // $('#ren').text(content.hasLoanNum); //贷款成功人数pc端无

            /***贷款类型***/
            var type = '';
            for (var i = 0, yg = content.tagList.length; i < yg; i++) {
                type += '<span>' + content.tagList[i] + '</span>'
            }

            $("#loansType").html(type);

            /***成功率***/
            var star = content.successRatio,
                a = star % 1;
            if (a == 0) {
                var lg = '';
                for (var i = 0; i < star; i++) {
                    lg += '<i><img src="publicImg/daikuanxiangqing-xing-pre@2x.png"></i>'
                }
                $('#star').append(lg)
            } else {
                var starS = Math.floor(star);
                var lg = '',
                    lgg = '<i><img src="publicImg/daikuanxiangqing-xing-ban@2x.png"></i>';
                for (var i = 0; i < starS; i++) {
                    lg += '<i><img src="publicImg/daikuanxiangqing-xing-pre@2x.png"></i>'
                }
                $('#star').append(lg + lgg)

            }

            /***额度范围***/
            var scope = content.loanLimitLow + '-' + content.loanLimitHigh;
            $('#scope').text(scope);

            /***期限范围***/
            var monut = content.timeLimitList.split(','), mtg = monut.length;
            if (monut[mtg - 1] == monut[0]) {
                $('#timeLimitList').html(monut[mtg - 1] + content.timeLimitUnit)
            } else {
                $('#timeLimitList').html(monut[0] + '-' + monut[mtg - 1] + content.timeLimitUnit)
            }

            var mon = content.timeLimitList.indexOf('-');

            if (mon == '-1') {
                var monut = content.timeLimitList.split(','), mtg = monut.length;

                if (monut[mtg - 1] == monut[0]) {
                    $('#timeLimitList').html(monut[mtg - 1] + content.timeLimitUnit)
                } else {
                    $('#timeLimitList').html(monut[0] + '-' + monut[mtg - 1] + content.timeLimitUnit)
                }

            } else {

                $('#timeLimitList').html(content.timeLimitList + content.timeLimitUnit)


            }

            /***利率***/

            $('#loanRateLoanRateUnit').html(content.loanRate + '%/' + content.loanRateUnit);


            /***产品详情***/

            var str = /\\r\\n/g,
                a1 = content.loanRequire,
                b1 = content.productDescription,
                c1 = content.sellerDescription;


            $('.requirementInner p').html(a1.replace(str, '<br>'));
            $('.productInfoInner p').html(b1.replace(str, '<br>'));
            $('.companyInfoInner p').html(c1.replace(str, '<br>'));

            /***立即申请***/
            if (content.display) {

                var replayObj = new Object();
                replayObj.url = content.applyUrl;
                replayObj.logour = geturlimg + content.logoUrl;
                replayObj.productname = content.name;
                replayObj.pcapply = false;  //是否支持电脑申请
                $('#replayThis').data(replayObj)


            } else {
                $('#replayThis').html('名额已用完').css({background: "#ccc"}).attr('disabled', 'disabled');

            }

            //获取社区帖子
            getcommunity(1)
        }else {

                defaultHint('数据获取中断返回上一页');
                window.location.href='index.html'

            }

        }
    });


    /******立即申请*******/

    $('.replayThis').click(function () {

        if(islogin()){
            let _this=$(this);
            let pcpcapply=_this.data('pcapply');
            let applyUrl=_this.data('url');
            let logoUrl=_this.data('logour');
            let productname=_this.data('productname');

            if(pcpcapply){
                upproductApply(applyUrl)
                // window.location.href=applyUrl;
            }else {
                upproductApply();

                $("#qrProductLogo").attr("src",logoUrl);

                $('#qrCodeBoxInner').html('');

                $('#qrproductname').html(productname);

                new QRCode(document.getElementById('qrCodeBoxInner'), applyUrl);
                $('.qr').show();

                $(".qr").click(function () {
                    $(this).hide();
                });
            }
        }else {
            $('#loginMode').show()
        }





        console.log($(this).data())

    });

    /****************************侧边栏热门帖子*********************************/

    sidebarfn('sidebarPost','.loansDetailHotPost');

    /****************************侧边栏最新贷款*********************************/

    sidebarfn('sidebarProduct','.NewLoansProductList');

    /****************************社区*********************************/



    var
        groupCommentTop = '967',
        groupComment = '',
        response = '',
        pro = '',
        listCurrentPage = 1
        , contentpage = ''  ///存放请求数据的页数
        , username = userInfo.name
        , prisession = sessionStorage.getItem('pri') //储存点赞的数据
        , pri = [];                                   //储存点赞的数据

    if (notNull(prisession)) {
        pri = prisession.split(',');
    }

    //获取页面点赞帖子的id
    function showPri() {
        for (var i = 0, plg = pri.length; i < plg; i++) {
            var className = "." + pri[i];
            $(className).attr('src', '../publicImg/zan_sel.png').data('type', true)
        }

    }

    //存储点赞Id
    function addPri(priid) {
        pri.push(priid);
        sessionStorage.setItem('pri', pri)
    }

    //删除点赞id
    function removePri(priid) {
        var idIndex = pri.indexOf(priid);

        if (idIndex == '-1') {
        } else {
            pri.splice(idIndex, 1);
            sessionStorage.setItem('pri', pri)
        }

    };


    let indexGroupPostList= $("#productGroupListInner");


    function getcommunity(listCurrentPage) {
        myAjaxFunc({
            url: community + "getPagePost",
            type: 'post',
            dataType: 'json',
            data: {groupId: groupId, listCurrentPage: listCurrentPage},
            mySuccess: function (data) {
                if (isResponseSuccess('success', data)) {
                    let postData = isResponseSuccess('getdata', data);
                    postData.list.roles = set_roles();   //配置管理员信息
                    postData.list.listCurrentPage = postData.extra.listCurrentPage;  //配置当前页
                    postData.list.geturl = geturlimg;     //配置图片加载地址
                    let leng = postData.list.length;

                    if(leng<0){
                        return
                    }

                    for (let i = 0; i < leng; i++) {
                        let imgList = '';
                        let imgUrl = postData.list[i].imgUrls;
                        if (notNull(imgUrl)) {
                            imgList = postData.list[i].imgUrls.split(',');
                        }
                        postData.list[i].imgUrls = imgList;
                        postData.list[i].textContentShort = html_encode(postData.list[i].textContentShort);

                    }


                    //配置图片为数组

                    let pageInfo = postData.extra,
                        allpage = pageInfo.listPageCount, //总页数
                        atpage = pageInfo.listCurrentPage; //当前页数

                    console.log(postData);

                    var html = template('loansDetail-post-list-template', postData);

                    indexGroupPostList.empty().append(html);

                    setTimeout(showPri(), 200);//返回显示点赞数据

                    creationPage(allpage,atpage);

                    // $(".hotLoanInnerRightBox").pin();

                    /*******点击图片********/
                    $('.Gallery').on('click', 'li', function () {
                        event.stopPropagation();
                        var innde = '<div class="swiper-container" ><div class="swiper-wrapper" ></div><div class="swiper-pagination"></div></div>';
                        var clickIndex = $(this).index(),
                            showBoxImg = '',
                            allImg = $(this).parent().find('img');
                        for (var i = clickIndex, ig = allImg.length, num = 0; num < ig;) {
                            if (i >= ig)
                                i = i - ig;
                            var src = allImg[i].currentSrc;
                            showBoxImg += '<div class="swiper-slide" ><img src="' + src + '"></div>';
                            i++;
                            num++;
                        }
                        $('#imgBox').append(innde);
                        $('.swiper-wrapper').append(showBoxImg);
                        $("body").on("touchmove", function (event) {
                            event.preventDefault;
                        }, false).addClass('over');
                        $('#imgBox').show();
                        var swiper = new Swiper('.swiper-container', {
                            pagination: '.swiper-pagination',
                            paginationType: 'fraction',
                            loop: true
                        });
                        $('#imgBox').click(function () {
                            $('#imgBox').hide().html('');
                            $('body').removeClass('over').off("touchmove");
                            swiper = ''
                        });
                        event.stopPropagation();

                    });//查看大图
                    changeImg();//更改图片样式
                }
            }
        });
    }



    function creationPage(allpage,atpage) {

        Page({
            num:allpage,			//页码数
            startnum:atpage,		//指定页码
            elem:$('#page'),		//指定的元素
            callback:function(n){	//回调函数
                getcommunity(n)
            }
        });
    }


    // creationPage(10,1)


    //优化图片显示
    function changeImg() {

        var _imgb = $('.postImg img');
        var postCoverImg = $('.postCoverImg');
        _imgb.load(function () {
            var Imgheight = $(this).height();
            var ImgWidth = $(this).width();
            if (Imgheight > ImgWidth) {
                $(this).addClass('forWidth')
            } else {
                $(this).addClass('forHeight')
            }

        })

        postCoverImg.load(function () {
            var Imgheight = $(this).height();
            var ImgWidth = $(this).width();
            if (Imgheight > ImgWidth) {
                $(this).addClass('forWidth')
            } else {
                $(this).addClass('forWidth')
            }

        })


    }

    changeImg();


    function getDistance(obj) {
        if (!obj instanceof jQuery) {
            obj = $(obj);
        }
        var distance = {};
        distance.top = (obj.offset().top - $(document).scrollTop());
        distance.bottom = ($(window).height() - distance.top - obj.outerHeight());
        distance.left = (obj.offset().left - $(document).scrollLeft());
        distance.right = ($(window).width() - distance.left - obj.outerWidth());
        return distance;
    }


    // setTimeout(function () {
    //     groupCommentTop=getDistance( $('.hotLoanInnerRightBox')).top;
    //     console.log('topboxtx'+groupCommentTop);
    //
    // },500)

    groupCommentTop=836;

    /*右边侧栏滚动显示*/

    $('.hotLoanInnerRightBox').show();


    $(document).scroll(function () {
        let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        , che = document.documentElement.scrollHeight - (document.documentElement.clientHeight + scrollTop);


        var rightboxtx=getDistance( $('.productInfo')).right;
        var bottomboxtx=getDistance( $('.productInfo')).bottom;
        // var topboxtx=getDistance( $('.hotLoanInnerRightBox')).top;
        //
        // console.log('topboxtx'+groupCommentTop);
        // console.log('bottomboxtx'+bottomboxtx);

        console.log(scrollTop)

        if(scrollTop>groupCommentTop){
            $('.hotLoanInnerRightBox').addClass('fixRight');
            $('.hotLoanInnerRightBox').css({'right':rightboxtx-340+'px'})
        }else {
            $('.hotLoanInnerRightBox').removeClass('fixRight');

        }

        if(bottomboxtx<-10){
            $('.hotLoanInnerRightBox').css({'right':rightboxtx-340+'px'})
            $('.hotLoanInnerRightBox').show();
            $('.hotLoanInnerRightBox').removeClass('positionBottom');

        }else {

            $('.hotLoanInnerRightBox').removeClass('fixRight').addClass('positionBottom');



        }


    });
    /*END*/

    // $(".hotLoanInnerRightBox").pin();







});



